package com.dbq.fast.business.login.business;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.analysis.EventConstant;
import com.dbq.fast.analysis.FireBaseUserPurchaseTrack;
import com.dbq.fast.analysis.YibaAnalysis;
import com.dbq.fast.business.login.NewLoginActivity;
import com.dbq.fast.business.login.api.NewLoginApi;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.product.event.FaceBookUserPurchaseTrack;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.manager.DatabaseManager;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.ApkUtils;
import com.dbq.fast.util.ProgressDialogUtil;
import com.dbq.fast.util.SystemUtil;
import com.dbq.fast.util.TimeOutHandler;
import com.dbq.fast.util.WindowToastUtils;

import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by yuanchen on 2018/5/22.
 */

public class NewLoginBiz {

    public static final int REASON_PHONE_FORMAT_ERROR = 0x00; //手机号格式不正确
    public static final int REASON_ACCOUNT_IS_EXIST = 0x01; //账号已存在，不能重复注册
    public static final int REASON_VER_CODE_ERROR = 0x02; //验证码错误
    public static final int REASON_PWD_NOT_SAME = 0x03; //两次密码输入不一致
    public static final int REASON_ACCOUNT_NOT_EXIST = 0x04; //账号不存在
    public static final int REASON_ACCOUNT_OR_PWD_ERROR = 0x05; //账号或密码错误

    private Activity context;
    private LoginListener listener;
    private TimeOutHandler timeOutHandler;
    static AtomicInteger mark;

    public NewLoginBiz(Activity context){
        this.context = context;
        accessParentInfo();
    }

    /**
     * 请求验证码
     */
    public void requestVerCode(String phone){
        NewLoginApi.accessVerifiCode(phone, new RemoteApiCallBack<String>() {
            @Override
            public void onFail(int status, String message) {
                if(status == 805){
                    if(listener != null){
                        listener.loginFail(REASON_ACCOUNT_IS_EXIST, message);
                    }
                }
            }

            @Override
            public void onSuccess(String s) {
                Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_verifi_code_send), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 请求验证码（重置密码）
     */
    public void requestPwdVerCode(String phone){
        NewLoginApi.accessPwdVerifiCode(phone, new RemoteApiCallBack<String>() {
            @Override
            public void onFail(int status, String message) {
                if(status == 805){
                    if(listener != null){
                        listener.loginFail(REASON_ACCOUNT_IS_EXIST, message);
                    }
                }
            }

            @Override
            public void onSuccess(String s) {
                Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_verifi_code_send), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 校验验证码
     */
    public void checkVerCode(String phone, String verifiCode){
        loginTimeOutHandler();
        NewLoginApi.checkVerifiCode(phone, verifiCode, new RemoteApiCallBack<String>() {
            @Override
            public void onFail(int status, String message) {
                if(mark != null) {
                    if (mark.get() == 2) return;
                    mark.set(3);
                }
                if(listener != null){
                    listener.checkVerCode(false);
                }
            }

            @Override
            public void onSuccess(String s) {
                if(mark != null) {
                    if (mark.get() == 2) {
                        return;
                    }
                    mark.set(1);
                }
                if(listener != null){
                    listener.checkVerCode(true);
                }
            }
        });
    }

    /**
     * 注册
     */
    public void register(String phone, String pwd, String captcha){
        loginTimeOutHandler();
        NewLoginApi.register(phone, pwd, captcha, new RemoteApiCallBack<CustomProfile>() {
            @Override
            public void onFail(int status, String message) {
                if(mark != null) {
                    if (mark.get() == 2) return;
                    mark.set(3);
                }
                if(listener != null){
                    listener.loginFail(status, message);
                }
            }

            @Override
            public void onSuccess(CustomProfile profile) {
                if(mark != null) {
                    if (mark.get() == 2) {
                        return;
                    }
                    mark.set(1);
                }
                handleSucc(profile);
                if(listener != null){
                    listener.loginSuccess(profile);
                }
            }
        });
    }

    /**
     * 登录
     */
    public void login(String account, String pwd){
        loginTimeOutHandler();
        NewLoginApi.login(account, pwd, new RemoteApiCallBack<CustomProfile>() {
            @Override
            public void onFail(int status, String message) {
                if(mark != null) {
                    if (mark.get() == 2) return;
                    mark.set(3);
                }
                if(listener != null){
                    listener.loginFail(status, message);
                }
            }

            @Override
            public void onSuccess(CustomProfile profile) {
                if(mark != null) {
                    if (mark.get() == 2) {
                        return;
                    }
                    mark.set(1);
                }
                handleSucc(profile);
                if(listener != null){
                    listener.loginSuccess(profile);
                }
            }
        });
    }

    /**
     * 重置密码
     */
    public void resetPwd(String phone, String pwd, String captcha){
        loginTimeOutHandler();
        NewLoginApi.resetPwd(phone, pwd, captcha, new RemoteApiCallBack<String>() {
            @Override
            public void onFail(int status, String message) {
                if(mark != null) {
                    if (mark.get() == 2) return;
                    mark.set(3);
                }
                if(listener != null){
                    listener.loginFail(status, message);
                }
            }

            @Override
            public void onSuccess(String s) {
                if(mark != null) {
                    if (mark.get() == 2) {
                        return;
                    }
                    mark.set(1);
                }
                if(listener != null){
                    listener.resetPwd(true, "");
                }
            }
        });
    }

    private void handleSucc(CustomProfile profile){
        YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_LOGIN_SUCC);
        FaceBookUserPurchaseTrack.loginEvent();
        FireBaseUserPurchaseTrack.login(App.getContext(),profile.getLoginChannel()+"");
        ProgressDialogUtil.hideProgress();
        Toast.makeText(App.getContext(), App.getContext().getString(R.string.tip_login_success), Toast.LENGTH_SHORT).show();
        DatabaseManager.getInstance().saveProfile(profile);
        User.getInstance().init();
        configUserId();
    }

    public void logOut(){
        DatabaseManager.getInstance().delAllProfile();
        User.getInstance().logOut();
    }

    /**
     * 配置log日志中的用户id
     */
    private void configUserId(){
        com.yiba.logutils.utils.LogConfig.setUid("".equals(User.getInstance().getAccount())? SystemUtil.getAndroidId(App.getContext()):User.getInstance().getAccount());
    }

    public void setLoginListener(LoginListener listener){
        this.listener = listener;
    }

    public interface LoginListener{
        void loginSuccess(CustomProfile profile);
        void loginFail(int type, String reason);
        void checkVerCode(boolean isOk);
        void resetPwd(boolean isOk, String msg);
    }

    /**
     * 获取上家VpnId
     */
    private void accessParentInfo() {
        String path = ApkUtils.getPackagePath(App.getContext());
        if (path == null) return;
        String parentId = ApkUtils.readApk(new File(path));
        if(parentId == null) {
            Bundle bundle = new Bundle();
            bundle.putString(EventConstant.PARAM_INVITE_BY, "self");
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_INSTALL_FROM, bundle);
            return;
        }else {
            Bundle bundle = new Bundle();
            bundle.putString(EventConstant.PARAM_INVITE_BY, parentId);
            YibaAnalysis.getInstance().event(App.getContext(), EventConstant.EVENT_INSTALL_FROM, bundle);

            User.getInstance().setParentId(parentId);
        }
//        Log.e("yc_", "apk parentId:"+parentId);
//        Log.e("yc_", "parentId:"+User.getInstance().getParentId());
    }

    private void loginTimeOutHandler() {
        if (mark == null) {
            mark = new AtomicInteger(0); //0：开始网络请求，1：网络请求成功，2：网络超时, 3：网络请求失败
        } else {
            mark.set(0);
        }
        if(timeOutHandler == null) {
            timeOutHandler = new TimeOutHandler();
        }
        timeOutHandler.setTimeOutListener(() -> {
            if(mark != null) {
                if (mark.get() == 1 || mark.get() == 3) {
                    return;
                }
                mark.set(2);
            }
            ProgressDialogUtil.hideProgress();
            if(context == null) return;
            if(((NewLoginActivity) context).isResume){
                context.runOnUiThread(() -> {
                    WindowToastUtils.showShort(App.getContext(), App.getContext().getString(R.string.tip_retry_network_bad));
                });
            }
        });
        timeOutHandler.startTiming();
    }

}
